package com.winit.openapi.claim.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.openapi.claim.builder.ClaimOrderBuilder;
import com.winit.openapi.claim.util.ClaimOrderRequest;
import com.winit.openapi.claim.validator.ClaimOrderValidator;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.exception.ValidationException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.HttpUtil;
import com.winit.openapi.util.ValidateUtil;

/**
 * 代客索赔API对接入口
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * minghao.deng 	1.0  		2017年3月31日 	Created
 *
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "valet/claim")
public class ValetClaimOrderController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(ValetClaimOrderController.class);

    @Resource
    private ClaimOrderBuilder   claimOrderBuilder;

    /**
     * 创建索赔单
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/create")
    public String createOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        ClaimOrderValidator.validateClaimOrder(json);
        Map<String, Object> data = claimOrderBuilder.buildClaimOrderRequest(json);
        ClaimOrderRequest request = new ClaimOrderRequest();
        request.setService("CaseClaim.addClaim");
        request.setData(data);

        postAndGetResult(request, responseMsg);

        if (ErrorCode.SUCCESS.equals(responseMsg.getCode())) {
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("orderId", responseMsg.getData());
            responseMsg.setData(result);
        }

        return SUCCESS;

    }

    /**
     * 更新索赔单，更新时候索赔单ID必填
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/update")
    public String updateOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        ValidateUtil.validNotNull(json, "orderId");
        ValidateUtil.validMaxLength(json, "orderId", 64, true);
        ClaimOrderValidator.validateClaimOrder(json);
        Map<String, Object> data = claimOrderBuilder.buildClaimOrderRequest(json);
        ClaimOrderRequest request = new ClaimOrderRequest();
        request.setService("CaseClaim.upClaim");
        request.setData(data);

        postAndGetResult(request, responseMsg);

        return SUCCESS;

    }

    /**
     * 评价索赔单
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/evaluate")
    public String evaluateOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        ValidateUtil.validNotNull(json, "orderId");
        ValidateUtil.validMaxLength(json, "orderId", 64, true);
        ValidateUtil.validNotNull(json, "evaluateLevel");
        ValidateUtil.validMaxLength(json, "evaluateLevel", 1, true);
        ValidateUtil.validByRegex(json, "evaluateLevel", "[1,2,3,4,5]", false);

        ValidateUtil.validNotNull(json, "evaluateDetails");
        ValidateUtil.validMaxLength(json, "evaluateDetails", 1024, true);
        Map<String, Object> data = claimOrderBuilder.buildClaimOrderEvaluate(json);
        ClaimOrderRequest request = new ClaimOrderRequest();
        request.setService("Case.evaluate");
        request.setData(data);

        postAndGetResult(request, responseMsg);

        return SUCCESS;

    }

    @RequestMapping(value = "/queryAcceptInfoById")
    public String queryAcceptInfoById(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        ValidateUtil.validNotNull(json, "orderId");
        ValidateUtil.validMaxLength(json, "orderId", 64, true);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("base_id", json.get("orderId"));
        data.put("ctx", json.get("ctx"));
        ClaimOrderRequest request = new ClaimOrderRequest();
        request.setService("CaseClaim.getAcceptById");
        request.setData(data);

        postAndGetResult(request, responseMsg);

        responseMsg.setData(claimOrderBuilder.buildAcceptInfoResponse(responseMsg));

        return SUCCESS;

    }

    @RequestMapping(value = "/queryOrderDetailById")
    public String queryOrderDetailById(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        ValidateUtil.validNotNull(json, "orderId");
        ValidateUtil.validMaxLength(json, "orderId", 64, true);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("base_id", json.get("orderId"));
        data.put("ctx", json.get("ctx"));
        ClaimOrderRequest request = new ClaimOrderRequest();
        request.setService("Case.getCaseById");
        request.setData(data);

        postAndGetResult(request, responseMsg);

        responseMsg.setData(claimOrderBuilder.buildOrderDetailResponse(responseMsg));

        return SUCCESS;

    }

    @RequestMapping(value = "/queryOrderList")
    public String queryOrderList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        ClaimOrderValidator.validateClaimOrderList(json);
        Map<String, Object> requestData = claimOrderBuilder.buildQueryOrderListRequest(json);
        ClaimOrderRequest request = new ClaimOrderRequest();
        request.setService("CaseClaim.getList");
        request.setData(requestData);

        postAndGetResult(request, responseMsg);

        responseMsg.setData(claimOrderBuilder.buildOrderListResponse(responseMsg));

        return SUCCESS;

    }

    private void postAndGetResult(ClaimOrderRequest request, ResponseMsg responseMsg) {
        String result = HttpUtil.postJson(config.getHelpCenterDomain(), JSONObject.toJSONString(request));
        if (StringUtils.isNotEmpty(result)) {
            JSONObject itemJson;
            try {
                itemJson = JSONObject.parseObject(result);
            } catch (Exception e) {
                logger.error("调用service:" + request.getService() + "返回值异常：" + result);
                throw new ApiException(ErrorCode.ILLEGAL_JSON_STRING);
            }
            String code = itemJson.getString("status");
            responseMsg.setMsg(itemJson.getString("msg"));
            responseMsg.setData(itemJson.get("data"));
            // 1表示操作成功 0表示操作失败，除此之外没有其他错误码
            if ("1".equals(code)) {
                responseMsg.setCode(ErrorCode.SUCCESS);
            } else {
                responseMsg.setCode(ErrorCode.SYSTEM_ERROR);
                throw new ValidationException(ErrorCode.SYSTEM_ERROR, itemJson.getString("msg"));
            }

        } else {
            logger.error("调用service:" + request.getService() + "返回值为空");
            throw new ApiException(ErrorCode.SYSTEM_ERROR);
        }

    }
}
